
import PoolRoom from "../../Entities/PoolRoom";
import LanguageMng from "../../Managers/LanguageMng";
import LanguageMngTs from "../../Managers/LanguageMngTs";

cc.Class({
    extends: cc.Component,

    properties: {
        svParent: {
            default: null,
            type: cc.Node
        },

        roomModel: {
            default: null,
            type: cc.Prefab
        },

        titleParent: {
            default: null,
            type: cc.Node
        },

        tabParent: {
            default: null,
            type: cc.Node
        },

        labelTotalPeople: {
            default: null,
            type: cc.Label
        },

        sortArrowSpriteNode: {
            default: null,
            type: cc.Node
        },

        scrollView: {
            default: null,
            type: require("BuzyScrollView")
        }

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.node.on("ui_update_people", this.updatePeopleCount.bind(this), this)
        this.node.on("ui_update_tab", this._selectTab.bind(this), this)
    },

    start() {
        this._selectTab("button_points")
    },

    // update (dt) {},

    updatePeopleCount: function () {
        if (!cc.gg.dataMgr.statistics)
            return

        this.labelTotalPeople.string = cc.gg.dataMgr.statistics.total
        for (let i = 0; i < this.svParent.children.length; i++) {
            let node = this.svParent.children[i]
            if (node.active) {
                this._updateOnePelpleCount(node)
                return
            }
        }
    },

    _updateOnePelpleCount: function (node) {
        if (!cc.gg.dataMgr.statistics)
            return

        let content = cc.find("sv/view/content", node)
        for (let i = 0; i < content.children.length; i++) {
            let item = content.children[i]
            let script = item.getComponent("lobby_room_item")
            let roomObj = script.roomObj
            if(!roomObj) break;
            let key = ""
            if (roomObj.type === cc.gg.enumConfig.RoomType.POINTS) {
                key = "point"
            } else if (roomObj.type === cc.gg.enumConfig.RoomType.DEAL) {
                key = "deal"
            } else if (roomObj.type === cc.gg.enumConfig.RoomType.POOL) {
                key = "pool"
            }

            for (let j = 0; j < cc.gg.dataMgr.statistics[key].length; j++) {
                let countObj = cc.gg.dataMgr.statistics[key][j]
                if (countObj.id === roomObj.id) {
                    script.updatePlayerCount(countObj.num)
                    // cc.logfl("更新"+key+"人数：",countObj.id," ",countObj.num)
                    break
                }
            }
        }
    },

    onLobbyTabsClicked: function (event) {
        cc.find("Canvas/SoundManager").getComponent("SoundManager").playKaPaiSound()
        let btnName = event.target.name
        this._selectTab(btnName)
    },

    onLobbyInfoButtonClicked: function (event) {
        cc.gg.tdUtil.doSendTdEvent("click_gameinfo", "LobbyBlue")
        this.showGameInfo(this.nowTab)
    },

    _selectTab: function (btnName) {
        btnName = btnName || this.nowTab
        this.nowTab = btnName
        for (let i = 0; i < this.tabParent.children.length; i++) {
            let node = this.tabParent.children[i]
            if (node.name === btnName) {
                node.color = new cc.color(255, 255, 255, 255)
            } else {
                node.color = new cc.color(180, 180, 180, 255)
            }
        }

        let nodeName = ""
        if (btnName === "button_points") {
            nodeName = "points"
            this.showOnlyOneContentNode(nodeName)
        } else if (btnName === "button_pool") {
            nodeName = "pool"
            this.showOnlyOneContentNode(nodeName)
        } else if (btnName === "button_deals") {
            nodeName = "deals"
            this.showOnlyOneContentNode(nodeName)
        } else if (btnName === "button_howtoplay") {

            let title = LanguageMng.getSentence(28)    //Practice
            let positiveStr = LanguageMng.getSentence(178)  //Enter
            let passiveStr = LanguageMng.getSentence(179)   //Cancel
            let contentStr = LanguageMngTs.getSentence(312) //Now,let's play with guild and learn to how to play this game.
            cc.gg.toastMgr.showDialog(title, positiveStr, passiveStr, contentStr,
                function () {
                    cc.gg.tdUtil.doSendTdEvent("click_howtoplay_tab", "Lobby")
                    cc.gg.dataMgr.playGuild = true
                    cc.director.loadScene('TwoPlayerGame')
                }.bind(this),
                function () {
                    cc.gg.toastMgr.removeDialog()
                }
            )
        }
    },

    showGameInfo: function (tabName) {
        if (tabName === "button_points") {
            let title = LanguageMng.getSentence(29) //Points
            let btnStr = LanguageMng.getSentence(181)   //ok
            let contentStr = LanguageMng.getSentence(112)   //Play for points which have a pre-decided value.One winner wins the complete prize pool at the end of each game
            let cb = function () {
                cc.gg.toastMgr.removeDialog()
            }.bind(this)
            cc.gg.toastMgr.showDialogOneButton(title, btnStr, contentStr, cb)
        } else if (tabName === "button_pool") {
            let title = LanguageMng.getSentence(159) //Pool
            let btnStr = LanguageMng.getSentence(181)   //ok
            let contentStr = LanguageMng.getSentence(143)   //Play for points which have a pre-decided value.One winner wins the complete prize pool at the end of each game
            let cb = function () {
                cc.gg.toastMgr.removeDialog()
            }.bind(this)
            cc.gg.toastMgr.showDialogOneButton(title, btnStr, contentStr, cb)
        } else if (tabName === "button_deals") {
            let title = LanguageMng.getSentence(30) //Deal
            let btnStr = LanguageMng.getSentence(181)   //ok
            let contentStr = LanguageMng.getSentence(113)   //Play for points which have a pre-decided value.One winner wins the complete prize pool at the end of each game
            let cb = function () {
                cc.gg.toastMgr.removeDialog()
            }.bind(this)
            cc.gg.toastMgr.showDialogOneButton(title, btnStr, contentStr, cb)
        }
    },

    showOnlyOneContentNode: function (nodeName, forceInit) {
        // for (let i = 0; i < this.svParent.children.length; i++) {
        //     let node = this.svParent.children[i]
        //     if (node.name === nodeName) {
        let node = cc.find("Canvas/content/svs/points")
        node.active = true
        this.initListNode(node, forceInit, nodeName)
        this.updateTitleLabels(node, nodeName)
        this._updateOnePelpleCount(node)
        //     } else node.active = false
        // }
    },

    turnSortArrowUp: function (isUp) {
        this.sortArrowSpriteNode.rotation = isUp ? 180 : 0
    },

    updateTitleLabels: function (node, nodeName) {
        if (nodeName === "points") {
            let levels = LanguageMng.getSentence(162)
            let pointValue = LanguageMng.getSentence(18)
            let entry = LanguageMng.getSentence(163)
            let players = LanguageMng.getSentence(35)
            let playernum = LanguageMng.getSentence(384)
            this.changeTitleLabels(levels, pointValue, entry, players, playernum)
        } else if (nodeName === "pool") {
            let levels = LanguageMng.getSentence(162)
            let entryFee = LanguageMng.getSentence(33)
            let bounus = LanguageMng.getSentence(37)
            let players = LanguageMng.getSentence(35)
            let playernum = LanguageMng.getSentence(384)
            this.changeTitleLabels(levels, entryFee, bounus, players, playernum)
        } else if (nodeName === "deals") {
            let levels = LanguageMng.getSentence(162)
            let entryFee = LanguageMng.getSentence(33)
            let bounus = LanguageMng.getSentence(37)
            let players = LanguageMng.getSentence(35)
            let playernum = LanguageMng.getSentence(384)
            this.changeTitleLabels(levels, entryFee, bounus, players, playernum)
        }
    },

    initListNode: function (node, forceInit, nodeName) {
        // if (node._inited && node.pMax === cc.find("Canvas").getComponent("LobbyMgr").playerCount && !forceInit) return
        node._inited = true
        node.pMax = cc.find("Canvas").getComponent("LobbyMgr").playerCount

        cc.log("初始化节点：", nodeName)
        if (nodeName === "points") {
            this.initPointsNode(node)
        } else if (nodeName === "pool") {
            this.initPoolNode(node)
        } else if (nodeName === "deals") {
            this.initDealNode(node)
        }
    },

    changeTitleLabels: function (levels, entryFee, bounus, players, playernum) {
        cc.find("name", this.titleParent).getComponent(cc.Label).string = levels
        cc.find("point_value", this.titleParent).getComponent(cc.Label).string = entryFee
        cc.find("entry_fee", this.titleParent).getComponent(cc.Label).string = bounus
        cc.find("player_count", this.titleParent).getComponent(cc.Label).string = players
        cc.find("player", this.titleParent).getComponent(cc.Label).string = playernum
    },

    initPointsNode: function (node) {
        let content = cc.find("sv/view/content", node)
        // content.removeAllChildren()

    let roomObjs = cc.gg.enumConfig.getRoomObjs(cc.gg.enumConfig.RoomType.POINTS, cc.find("Canvas").getComponent("LobbyMgr").playerCount)
        cc.log("初始化point content：", roomObjs)

        this._initPointContentNode(content, roomObjs)
    },

    initPoolNode: function (node) {
        let content = cc.find("sv/view/content", node)
        // content.removeAllChildren()

        let roomObjs = cc.gg.enumConfig.getRoomObjs(cc.gg.enumConfig.RoomType.POOL, cc.find("Canvas").getComponent("LobbyMgr").playerCount)
        cc.log("初始化pool content：", roomObjs)

        this._initContentNode(content, roomObjs)
    },

    initDealNode: function (node) {
        let content = cc.find("sv/view/content", node)
        // content.removeAllChildren()

        let roomObjs = cc.gg.enumConfig.getRoomObjs(cc.gg.enumConfig.RoomType.DEAL, cc.find("Canvas").getComponent("LobbyMgr").playerCount)
        cc.log("初始化pool content：", roomObjs)

        this._initContentNode(content, roomObjs)
    },

    _initContentNode: function (content, roomObjs) {
        let info = cc.gg.dataMgr.getPlayerInfo()
        let array1 = [];
        let array2 = [];
        if (info) {
            let totalCoin = info.deposit + info.winnings
            for (let i = 0; i < roomObjs.length; i++) {
                if (roomObjs[i].e_fee <= Number(totalCoin)) {
                    array1.push({ data: roomObjs[i], index: i, id: 2 });
                } else {
                    array2.push({ data: roomObjs[i], index: i, id: 2 });
                }
            }
            array1.sort((a, b) => {
                return b.data.e_fee - a.data.e_fee;
            })

            array1 = array1.concat(array2);

        } else {
            for (let i = 0; i < roomObjs.length; i++) {
                array1.push({ data: roomObjs[i], index: i, id: 2 });
            }
        }

        for (let i = 0; i < content.children.length; i++) {
            let itemnode = content.children[i];
            itemnode.getComponent("lobby_room_item").initLobbyRoomItem(null, null, null, null, null);
        }

        this.initSv(this.scrollView, array1)

        // for (let i = 0; i < array1.length; i++) {
        //     let obj = array1[i]
        //     let itemNode = content.children[i]
        //     if (!itemNode) {
        //         itemNode = cc.instantiate(this.roomModel)
        //         content.addChild(itemNode)
        //     }

        //     let color
        //     if (i % 2 === 0) {
        //         color = (new cc.color()).fromHEX("#4762A4")
        //     } else {
        //         color = (new cc.color()).fromHEX("#354e8d")
        //     }
        //     itemNode.getComponent("lobby_room_item").initLobbyRoomItem(color, obj.name, obj.e_fee, obj.e_fee * obj.p_max, obj.p_max)
        //     itemNode.getComponent("lobby_room_item").roomObj = obj
        // }
    },

    _initPointContentNode: function (content, roomObjs) {
        let info = cc.gg.dataMgr.getPlayerInfo()
        let array1 = [];
        let array2 = [];
        if (info) {
            let totalCoin = info.deposit + info.winnings
            for (let i = 0; i < roomObjs.length; i++) {
                if (roomObjs[i].e_fee <= Number(totalCoin)) {
                    array1.push({ data: roomObjs[i], index: i, id: 1 });
                } else {
                    array2.push({ data: roomObjs[i], index: i, id: 1 });
                }
            }
            array1.sort((a, b) => {
                return b.data.e_fee - a.data.e_fee;
            })

            array1 = array1.concat(array2);

        } else {
            for (let i = 0; i < roomObjs.length; i++) {
                array1.push({ data: roomObjs[i], index: i, id: 1 });
            }
        }

        for (let i = 0; i < content.children.length; i++) {
            let itemnode = content.children[i];
            itemnode.getComponent("lobby_room_item").initLobbyRoomItem(null, null, null, null, null);
        }

        this.initSv(this.scrollView, array1)

        // for (let i = 0; i < array1.length; i++) {
        //     let obj = array1[i]
        //     let itemNode = content.children[i]
        //     if (!itemNode) {
        //         itemNode = cc.instantiate(this.roomModel)
        //         content.addChild(itemNode)
        //     }

        //     let color
        //     if (i % 2 === 0) {
        //         color = (new cc.color()).fromHEX("#4762A4")
        //     } else {
        //         color = (new cc.color()).fromHEX("#354e8d")
        //     }
        //     itemNode.getComponent("lobby_room_item").initLobbyRoomItem(color, obj.name, obj.multi, obj.e_fee, obj.p_max)
        //     itemNode.getComponent("lobby_room_item").roomObj = obj
        // }
    },

    initSv: function (busySv, array) {
        cc.log("列表将要显示数据：", array)
        busySv.noRemoveClearBuzyScrollView()
        busySv.initialize(array)
    },
});
